package com.hdu.hot100.graph;

public class lc200 {
    class Solution {
        int[][] directions = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}};


        public int numIslands(char[][] grid) {
            int ans = 0;
            int m = grid.length;
            int n = grid[0].length;
            for (int i = 0; i < m; i++)
            {
                for (int j = 0; j < n; j++)
                {
                    if (grid[i][j] == '1')
                    {
                        ans++;
                        f(grid, i, j);
                    }
                }
            }
            return ans;
        }

        void f(char[][] grid, int row, int col) {
            if (row < 0 || col < 0 || row >= grid.length || col >= grid[0].length) {
                return;
            }
            if (grid[row][col] != '1') {
                return;
            }
            grid[row][col] = '2';
            for (int[] direction : directions)
            {
                int nextRow = row + direction[0];
                int nextCol = col + direction[1];
                f(grid, nextRow, nextCol);
            }
        }
    }
}
